package com.ssy.lingxi.member.merchant.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import com.ssy.lingxi.member.merchant.model.vo.login.response.CaptchaPicVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.Base64Utils;
import org.springframework.util.ResourceUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class VerifyImageUtil {

    private static Logger log = LoggerFactory.getLogger(VerifyImageUtil.class);

    private static int BOLD = 5;

    private static final String IMG_FILE_TYPE = "jpg";

    private static final String TEMP_IMG_FILE_TYPE = "png";

    private static File[] imgFiles ;

    private static File templatesFile ;

    private static ThreadLocalRandom random = ThreadLocalRandom.current();

    /**
     * 根据模板切图
     * @param width 宽
     * @param height 高
     * @param size 尺寸
     * @return 滑块验证图
     * @throws Exception 文件不存在异常
     */
    public static CaptchaPicVO pictureTemplatesCut(String width,String height,String size) throws Exception {
        // 模板图
//        BufferedImage imageTemplate = ImageIO.read(getTemplatesFile());
        int templateWidth = new Integer(width);
        int templateHeight = new Integer(height);
        int temSize = new Integer(size);

        // 原图
        BufferedImage oriImage = ImageIO.read(getImgFile());
        BufferedImage newSizeImg = resize(oriImage, templateWidth, templateHeight);
        int oriImageWidth = newSizeImg.getWidth();
        int oriImageHeight = newSizeImg.getHeight();

        // 随机生成抠图坐标X,Y
        // X轴距离右端targetWidth Y轴距离底部targetHeight以上
        Random random = new Random();
        int widthRandom = random.nextInt(oriImageWidth - 2 * temSize) + temSize;
        // int heightRandom = 1;
        int heightRandom = random.nextInt(oriImageHeight - temSize);
        log.info("原图大小{} x {},随机生成的坐标 X,Y 为（{}，{}）", oriImageWidth, oriImageHeight, widthRandom, heightRandom);

        ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();// 新建流。
        ImageIO.write(newSizeImg, TEMP_IMG_FILE_TYPE, newImageOs);// 利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流。
        byte[] newImagebyte = newImageOs.toByteArray();

        CaptchaPicVO picVO = new CaptchaPicVO();
        picVO.setBackImage(Base64Utils.encodeToString(newImagebyte));
        picVO.setWidth(String.valueOf(widthRandom));
        picVO.setHeight(heightRandom);
        return picVO;
    }

    /**
     * 添加水印
     * @param oriImage 原图
     * @param templateImage 模板图
     * @param newImage 新抠出的小图
     * @param x 随机扣取坐标X
     * @param y 随机扣取坐标y
     */
    private static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage, int x, int y) {
        // 临时数组遍历用于高斯模糊存周边像素值
        int[][] martrix = new int[3][3];
        int[] values = new int[9];

        int xLength = templateImage.getWidth();
        int yLength = templateImage.getHeight();
        // 模板图像宽度
        for (int i = 0; i < xLength; i++) {
            // 模板图片高度
            for (int j = 0; j < yLength; j++) {
                // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
                int rgb = templateImage.getRGB(i, j);
                if (rgb < 0) {
                    newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j));

                    // 抠图区域高斯模糊
                    readPixel(oriImage, x + i, y + j, values);
                    fillMatrix(martrix, values);
                    oriImage.setRGB(x + i, y + j, avgMatrix(martrix));
                }

                // 防止数组越界判断
                if (i == (xLength - 1) || j == (yLength - 1)) {
                    continue;
                }
                int rightRgb = templateImage.getRGB(i + 1, j);
                int downRgb = templateImage.getRGB(i, j + 1);
                // 描边处理，,取带像素和无像素的界点，判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
                if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0)
                        || (rgb < 0 && downRgb >= 0)) {
                    newImage.setRGB(i, j, Color.white.getRGB());
                    oriImage.setRGB(x + i, y + j, Color.white.getRGB());
                }
            }
        }
    }

    private static void readPixel(BufferedImage img, int x, int y, int[] pixels) {
        int xStart = x - 1;
        int yStart = y - 1;
        int current = 0;
        for (int i = xStart; i < 3 + xStart; i++)
            for (int j = yStart; j < 3 + yStart; j++) {
                int tx = i;
                if (tx < 0) {
                    tx = -tx;

                }
                else if (tx >= img.getWidth()) {
                    tx = x;
                }
                int ty = j;
                if (ty < 0) {
                    ty = -ty;
                }
                else if (ty >= img.getHeight()) {
                    ty = y;
                }
                pixels[current++] = img.getRGB(tx, ty);

            }
    }

    private static void fillMatrix(int[][] matrix, int[] values) {
        int filled = 0;
        for (int[] x : matrix) {
            for (int j = 0; j < x.length; j++) {
                x[j] = values[filled++];
            }
        }
    }

    private static int avgMatrix(int[][] matrix) {
        int r = 0;
        int g = 0;
        int b = 0;
        for (int[] x : matrix) {
            for (int j = 0; j < x.length; j++) {
                if (j == 1) {
                    continue;
                }
                Color c = new Color(x[j]);
                r += c.getRed();
                g += c.getGreen();
                b += c.getBlue();
            }
        }
        return new Color(r / 8, g / 8, b / 8).getRGB();
    }

    public static String getImgId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    private static BufferedImage resize(BufferedImage img, int newW, int newH) {
        Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
        BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = dimg.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();

        return dimg;
    }

    /**
     * 读取Resouce目录下的图片文件
     * @return 输入流
     * @throws Exception 文件不存在异常
     */
    public static InputStream getImgFile() throws Exception {
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources(ResourceUtils.CLASSPATH_URL_PREFIX + "sliderImage/img/*.jpg");
        Assert.isTrue(ArrayUtil.isNotEmpty(resources),"本地文件资源为空，请联系管理员");
        Resource resource = resources[random.nextInt(resources.length)];
        InputStream img = resource.getInputStream();
        Assert.notNull(img,"本地文件资源为空，请联系管理员");
        return img;
    }
}